<!--  -->
<script setup>
import { useToast } from 'wot-design-uni'

const props = defineProps({
  // 允许上传的文件大小(MB)
  size: {
    type: Number,
    default: 3,
  },
})

const toast = useToast()

const fileList = ref([])
const action = ref('https://finance.swtsk.com/oss/upload')

const value = defineModel({ type: String, default: '' })

const stopProp = watch(() => value.value, () => {
  if (!value.value) {
    fileList.value = []
  }
  else {
    if (fileList.value.length)
      return
    value.value.split(',').forEach((url) => {
      fileList.value.push({
        url,
      })
    })
  }
}, { immediate: true })

onUnmounted(() => {
  stopProp()
})

const beforeUpload = ({ files, resolve }) => {
  const flag = files.map(({ size }) => (size / 1024 / 1024)).every(item => item <= props.size)
  if (!flag) {
    toast.error(`文件大小不能超过${props.size}MB`)
    return resolve(false)
  }
  resolve(true)
}
const handleError = (err) => {
  toast.error(err)
}

const remove = ({ file }) => {
  const arr = fileList.value.map((item) => {
    if (item.response) {
      return JSON.parse(item.response).url
    }
    else {
      return item.url
    }
  })
  value.value = arr.filter(item => item !== file.url).join(',')
}

const success = ({ fileList }) => {
  const arr = fileList.map((item) => {
    if (item.response) {
      return JSON.parse(item.response).url
    }
    else {
      return item.url
    }
  })
  value.value = arr.join(',')
}
</script>

<template>
  <div>
    <wd-toast />
    <wd-upload v-bind="$attrs" v-model:file-list="fileList" image-mode="aspectFill" :action="action" :before-upload="beforeUpload" @fail="handleError" @success="success" @remove="remove" />
  </div>
</template>

<style scoped lang='scss'>

</style>
